package com.xpqh.ksg.modular.warranty.service;


import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xpqh.ksg.base.BaseResponseDTO;
import com.xpqh.ksg.common.enums.result.BizExceptionEnum;
import com.xpqh.ksg.common.enums.result.BizSuccessEnum;
import com.xpqh.ksg.common.persistence.dao.KsgCarmembraneInfoMapper;
import com.xpqh.ksg.common.persistence.dao.KsgProductItemMapper;
import com.xpqh.ksg.common.persistence.dao.KsgWarrantyInfoMapper;
import com.xpqh.ksg.common.persistence.model.*;
import com.xpqh.ksg.common.utils.ImageInfoFetcher;
import com.xpqh.ksg.exception.WebApiException;
import com.xpqh.ksg.modular.warranty.dto.*;
import common.utils.StringUtils;
import common.utils.aliyun.AliyunSmsUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.util.*;

import static common.utils.aliyun.AliyunSmsUtils.createClient;

@Service
public class WarrantyService {

    @Autowired
    private KsgWarrantyInfoMapper warrantyInfoMapper;
    @Autowired
    private KsgCarmembraneInfoMapper ksgCarmembraneInfoMapper;

    @Autowired
    private KsgProductItemMapper ksgProductItemMapper;

    /**
     * 根据电话号码获取质保列表
     * @param phone
     * @return
     */
    public List<KsgWarrantyInfo> getWarrantyList(String phone) {
        List<KsgWarrantyInfo> warrntyList = warrantyInfoMapper.getWarrntyList(phone);
        for (KsgWarrantyInfo ksgWarrantyInfo : warrntyList) {
            ksgWarrantyInfo.setKsgCarmembraneInfoList(warrantyInfoMapper.getCarMembraneList(ksgWarrantyInfo.getWarrantyNumber()));
        }
        return warrntyList;
    }


    /**
     * 质保录入
     * @param req
     * @return
     */
    @Transactional
    public BaseResponseDTO saveWarranty(KsgAddWarrantyInfoReqDTO req) {
        KsgStoreInfo storeInfo = warrantyInfoMapper.getStoreInfo(req.getUserId());
        // 判断用户是否是管理员是否有录入权限
        if (null == storeInfo || null == storeInfo.getAutoId()) {
            return new BaseResponseDTO(BizExceptionEnum.NO_PERMISSION);
        }
        String[] signalIdArr = req.getSignalIdInfo().split(",");

        // 生成卷芯码
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssms");
        String warrantyNumber = sdf.format(new Date());
        String signalIds = "";
        // 保存质保卷芯码列表
        for(int i = 0; i < signalIdArr.length; i ++){
            String signalId = signalIdArr[i];

            KsgStockInfo stockInfo = warrantyInfoMapper.getBySignalId(signalId);
            if (stockInfo == null) {
                throw new WebApiException(BizExceptionEnum.PRODUCT_ERROR1);
            }
            if (!stockInfo.getStoreId().equals(storeInfo.getAutoId())) {
                throw new WebApiException(BizExceptionEnum.PRODUCT_ERROR4);
            }
            if (stockInfo.getUseNum() < 1) {
                throw new WebApiException(BizExceptionEnum.PRODUCT_ERROR2);
            }
            if (StringUtils.isNotBlank(signalIds)) {
                signalIds += "," + signalId;
            } else {
                signalIds = signalId;
            }
            KsgProductInfo productInfo = warrantyInfoMapper.getProductInfoBySignalId(signalId);
            String productMode = productInfo.getProductName();
            String productCode = productInfo.getProductCode();
            String productBatch = "";
            String productBox = "";
            Integer modeType = productInfo.getType().intValue();
            Integer windowType = productInfo.getWindowType().intValue();
            String qualityWarrantyYears = productInfo.getTerm() + "年";
            KsgCarmembraneInfo KsgCarmembraneInfo = new KsgCarmembraneInfo();
            KsgCarmembraneInfo.setWarrantyId(warrantyNumber);
            KsgCarmembraneInfo.setProductBatch(productBatch);
            KsgCarmembraneInfo.setProductBox(productBox);
            KsgCarmembraneInfo.setProductModel(productMode);
            KsgCarmembraneInfo.setProductCode(productCode);
            KsgCarmembraneInfo.setSignalId(req.getSignalIdInfo());
            KsgCarmembraneInfo.setType(modeType);
            KsgCarmembraneInfo.setWindowType(windowType);
            KsgCarmembraneInfo.setQualityWarrantyYears(qualityWarrantyYears);
            ksgCarmembraneInfoMapper.insert(KsgCarmembraneInfo);
            Integer useNum = stockInfo.getUseNum().intValue() - 1;
            Integer useType = 2;
            if (useNum == 0) {
                useType = 1;
            }
            warrantyInfoMapper.updateStockInfo(signalId,useNum,useType);
        }

        // 保存质保信息
        KsgWarrantyInfo KsgWarrantyInfo = new KsgWarrantyInfo();
        KsgWarrantyInfo.setStoreName(storeInfo.getStoreName());
        KsgWarrantyInfo.setPhone(req.getPhone());
        KsgWarrantyInfo.setStoreNumber(storeInfo.getStoreNo());
        KsgWarrantyInfo.setOfficeCode(storeInfo.getStoreNo());
        KsgWarrantyInfo.setStorePhone(storeInfo.getStorePhone());
        KsgWarrantyInfo.setStroeAddress(storeInfo.getStoreAddress());
        KsgWarrantyInfo.setVehicleBrand(req.getVehicleBrand());
        KsgWarrantyInfo.setVehicleModel(req.getVehicleModel());
        KsgWarrantyInfo.setLicensePlate(req.getLicensePlate());
        KsgWarrantyInfo.setFrameNumber(req.getFrameNumber());
        KsgWarrantyInfo.setConstructionDate(req.getConstructionDate());
        KsgWarrantyInfo.setCreateTime(new Date());
        KsgWarrantyInfo.setUpdateTime(new Date());
        KsgWarrantyInfo.setOperator(storeInfo.getOperatorName());
        KsgWarrantyInfo.setUserCode(storeInfo.getUserCode());
        KsgWarrantyInfo.setVehiclePrice(req.getVehiclePrice());
        KsgWarrantyInfo.setPosition(req.getPosition());
        KsgWarrantyInfo.setOwnerName(req.getUserName());
        KsgWarrantyInfo.setPictureList(req.getPictureList());
        KsgWarrantyInfo.setSignalId(signalIds);
        KsgWarrantyInfo.setWarrantyNumber(warrantyNumber);
        KsgWarrantyInfo .setMergedQrPicture(req.getMergedQrPicture());
        KsgWarrantyInfo.setQxImg(req.getQxImgList());
        KsgWarrantyInfo.setMdImg(req.getMdImg());
        warrantyInfoMapper.insert(KsgWarrantyInfo);
        try {
            KsgProductInfo productInfoBySignalId = warrantyInfoMapper.getProductInfoBySignalId(KsgWarrantyInfo.getSignalId());
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
            Map<String,String> map = new HashMap<>();
            map.put("time1",sdf2.format(KsgWarrantyInfo.getConstructionDate()));
            map.put("storeName",KsgWarrantyInfo.getStoreName());
            map.put("model",productInfoBySignalId.getProductName());
            map.put("num",productInfoBySignalId.getTerm()+"");
            map.put("time2",sdf2.format(KsgWarrantyInfo.getConstructionDate()));
            map.put("storeName1",KsgWarrantyInfo.getStoreName());
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                com.aliyun.dysmsapi20170525.Client client = AliyunSmsUtils.createClient("LTAI4GDGaV5FwczQHGVRUvY8", "GuN4vuPGtvc9V4GtF5W7THvUt65LYz");
                SendSmsRequest sendSmsRequest = new SendSmsRequest()
                        .setPhoneNumbers(KsgWarrantyInfo.getPhone())
                        .setSignName("KSG汽车膜")
                        .setTemplateCode("SMS_489810519")
                        .setTemplateParam(objectMapper.writeValueAsString(map));
                // 复制代码运行请自行打印 API 的返回值
                SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
                System.out.println(sendSmsResponse);
                warrantyInfoMapper.changeInfo(KsgWarrantyInfo.getWarrantyNumber(),KsgWarrantyInfo.getConstructionDate());
            }catch (Exception e) {
                e.printStackTrace();
            }
//			Map<String,String> map2 = new HashMap<>();
//			map2.put("time1",sdf2.format(sdf1.parse(ksgWarrantyInfo.getConstructionDate())));
//			map2.put("storeName",ksgWarrantyInfo.getStoreName());
//			map2.put("model",productInfoBySignalId.getProductName());
//			map2.put("time2",sdf2.format(sdf1.parse(ksgWarrantyInfo.getConstructionDate())));
//			Calendar calendar = Calendar.getInstance();
//			calendar.add(Calendar.YEAR, 1);
//			map2.put("time3",sdf2.format(calendar.getTime()));
//			map2.put("phone",ksgWarrantyInfo.getStorephone());
//			Runnable runnable = new Runnable() {
//				@Override
//				public void run() {
//					try {
//						Thread.sleep(10000);
//						com.aliyun.dysmsapi20170525.Client client = createClient("LTAI4GDGaV5FwczQHGVRUvY8", "GuN4vuPGtvc9V4GtF5W7THvUt65LYz");
//						SendSmsRequest sendSmsRequest = new SendSmsRequest()
//								.setPhoneNumbers(ksgWarrantyInfo.getPhone())
//								.setSignName("KSG汽车膜")
//								.setTemplateCode("SMS_472245318")
//								.setTemplateParam(objectMapper.writeValueAsString(map2));
//						// 复制代码运行请自行打印 API 的返回值
//						SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
//						System.out.println(sendSmsResponse);
//					}catch (Exception e) {
//						e.printStackTrace();
//					}
//				}
//			};
        }catch (Exception e) {
            e.printStackTrace();
        }
        try {
            String warrantyId = warrantyInfoMapper.getWarrantyId(warrantyNumber);
            String[] urls =  KsgWarrantyInfo.getPictureList().split("\\|");
            Integer sort = 10;
            for (String url : urls) {
                ImageinfoDto imageInfo = ImageInfoFetcher.getImageInfo(url);
                ImageuploadDto imageuploadDto = new ImageuploadDto();
                imageuploadDto.setId(String.valueOf(Long.valueOf(imageInfo.getFileid()) + 1));
                imageuploadDto.setFileid(imageInfo.getFileid());
                imageuploadDto.setFilename(imageInfo.getFileMd5()+"."+imageInfo.getExtension());
                imageuploadDto.setFiletype("image");
                imageuploadDto.setFilesort(sort);
                sort = sort + 10;
                imageuploadDto.setBizkey(warrantyId);
                imageuploadDto.setBiztype("ksg_pic");
                imageuploadDto.setStatus(0);
                imageuploadDto.setCreateTime(new Date());
                imageuploadDto.setUpdateTime(new Date());
                imageuploadDto.setCreateUser(storeInfo.getUserCode());
                imageuploadDto.setUpdateUser(storeInfo.getUserCode());
                warrantyInfoMapper.insertFileEntity(imageInfo);
                warrantyInfoMapper.insertFileUploadEntity(imageuploadDto);
            }
            String[] merpic = KsgWarrantyInfo.getMergedQrPicture().split("\\|");
            sort = 10;
            for (String url : merpic) {
                ImageinfoDto imageInfo = ImageInfoFetcher.getImageInfo(url);
                ImageuploadDto imageuploadDto = new ImageuploadDto();
                imageuploadDto.setId(String.valueOf(Long.valueOf(imageInfo.getFileid()) + 1));
                imageuploadDto.setFileid(imageInfo.getFileid());
                imageuploadDto.setFilename(imageInfo.getFileMd5()+"."+imageInfo.getExtension());
                imageuploadDto.setFiletype("image");
                imageuploadDto.setFilesort(sort);
                sort = sort + 10;
                imageuploadDto.setBizkey(warrantyId);
                imageuploadDto.setBiztype("ksg_signalPicture");
                imageuploadDto.setStatus(0);
                imageuploadDto.setCreateTime(new Date());
                imageuploadDto.setUpdateTime(new Date());
                imageuploadDto.setCreateUser(storeInfo.getUserCode());
                imageuploadDto.setUpdateUser(storeInfo.getUserCode());
                warrantyInfoMapper.insertFileEntity(imageInfo);
                warrantyInfoMapper.insertFileUploadEntity(imageuploadDto);
            }
            String[] qximg = KsgWarrantyInfo.getQxImg().split("\\|");
            sort = 10;
            for (String url : qximg) {
                ImageinfoDto imageInfo = ImageInfoFetcher.getImageInfo(url);
                ImageuploadDto imageuploadDto = new ImageuploadDto();
                imageuploadDto.setId(String.valueOf(Long.valueOf(imageInfo.getFileid()) + 1));
                imageuploadDto.setFileid(imageInfo.getFileid());
                imageuploadDto.setFilename(imageInfo.getFileMd5()+"."+imageInfo.getExtension());
                imageuploadDto.setFiletype("image");
                imageuploadDto.setFilesort(sort);
                sort = sort + 10;
                imageuploadDto.setBizkey(warrantyId);
                imageuploadDto.setBiztype("ksg_qxImg");
                imageuploadDto.setStatus(0);
                imageuploadDto.setCreateTime(new Date());
                imageuploadDto.setUpdateTime(new Date());
                imageuploadDto.setCreateUser(storeInfo.getUserCode());
                imageuploadDto.setUpdateUser(storeInfo.getUserCode());
                warrantyInfoMapper.insertFileEntity(imageInfo);
                warrantyInfoMapper.insertFileUploadEntity(imageuploadDto);
            }
            String[] mdimg = KsgWarrantyInfo.getMdImg().split("\\|");
            sort = 10;
            for (String url : mdimg) {
                ImageinfoDto imageInfo = ImageInfoFetcher.getImageInfo(url);
                ImageuploadDto imageuploadDto = new ImageuploadDto();
                imageuploadDto.setId(String.valueOf(Long.valueOf(imageInfo.getFileid()) + 1));
                imageuploadDto.setFileid(imageInfo.getFileid());
                imageuploadDto.setFilename(imageInfo.getFileMd5()+"."+imageInfo.getExtension());
                imageuploadDto.setFiletype("image");
                imageuploadDto.setFilesort(sort);
                sort = sort + 10;
                imageuploadDto.setBizkey(warrantyId);
                imageuploadDto.setBiztype("ksg_mdImg");
                imageuploadDto.setStatus(0);
                imageuploadDto.setCreateTime(new Date());
                imageuploadDto.setUpdateTime(new Date());
                imageuploadDto.setCreateUser(storeInfo.getUserCode());
                imageuploadDto.setUpdateUser(storeInfo.getUserCode());
                warrantyInfoMapper.insertFileEntity(imageInfo);
                warrantyInfoMapper.insertFileUploadEntity(imageuploadDto);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            return new BaseResponseDTO(BizSuccessEnum.OK);
        }
    }

    public static String getTime(Date currentTime,Date firstTime){
        long diff = currentTime.getTime() - firstTime.getTime();//这样得到的差值是微秒级别
        Calendar  currentTimes =dataToCalendar(currentTime);//当前系统时间转Calendar类型
        Calendar  firstTimes =dataToCalendar(firstTime);//查询的数据时间转Calendar类型
        int year = currentTimes.get(Calendar.YEAR) - firstTimes.get(Calendar.YEAR);//获取年
        int month = currentTimes.get(Calendar.MONTH) - firstTimes.get(Calendar.MONTH);
        int day = currentTimes.get(Calendar.DAY_OF_MONTH) - firstTimes.get(Calendar.DAY_OF_MONTH);
        if (day < 0) {
            month -= 1;
            currentTimes.add(Calendar.MONTH, -1);
            day = day + currentTimes.getActualMaximum(Calendar.DAY_OF_MONTH);//获取日
        }
        if (month < 0) {
            month = (month + 12) % 12;//获取月
            year--;
        }
        long days = diff / (1000 * 60 * 60 * 24);
        long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60); //获取时
        long minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);  //获取分钟
        long s=(diff/1000-days*24*60*60-hours*60*60-minutes*60);//获取秒
        String CountTime=""+year+"年"+month+"月"+day+"天"+hours+":"+minutes;
        return CountTime;
    }
    public static Calendar dataToCalendar(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }

    public KsgWarrantyInfo getWarrantyDetails(@NotNull(message = "质保Id不能为空") Integer warrantyId) {
        KsgWarrantyInfo ksgWarrantyInfo = warrantyInfoMapper.getWarrntyDetails(warrantyId);
        ksgWarrantyInfo.setKsgCarmembraneInfoList(warrantyInfoMapper.getCarMembraneList(ksgWarrantyInfo.getWarrantyNumber()));
        for (KsgCarmembraneInfo ksgCarmembraneInfo : ksgWarrantyInfo.getKsgCarmembraneInfoList()) {
            if (ksgCarmembraneInfo.getProductCode().equals("C858510")) {
                ksgCarmembraneInfo.setTcName("皇家至尊护理保养美容年卡");
                ksgWarrantyInfo.setIsCartec(1);
            } else if (ksgCarmembraneInfo.getProductCode().equals("C808007")) {
                ksgCarmembraneInfo.setTcName("镀晶护理保养美容年卡");
                ksgWarrantyInfo.setIsCartec(1);
            } else if (ksgCarmembraneInfo.getProductCode().equals("C757505")) {
                ksgCarmembraneInfo.setTcName("镀晶护理保养美容年卡");
                ksgWarrantyInfo.setIsCartec(1);
            }
            ksgCarmembraneInfo.setKsgProductItemList(ksgProductItemMapper.selectList(new QueryWrapper<KsgProductItem>().eq("product_code", ksgCarmembraneInfo.getProductCode())));
        }
        return ksgWarrantyInfo;
    }
}

